//
//  GPChatController+Message.m
//  GuaPi
//
//  Created by 陈华 on 2017/6/22.
//  Copyright © 2017年 Joanlove. All rights reserved.
//

#import "GPChatController+Message.h"
#import "GPMessageItem.h"
#import "GPDeviceManager.h"
#import "GPProfileItem.h"                           //存储用户的头像昵称模型
#import "KUserData.h"

@implementation GPChatController (Message)

#pragma mark - 消息相关的工具方法
/**向数据源中追加消息（判断是否显示时间）*/
- (void)messageArray:(NSMutableArray *)messages addMessage:(GPMessageItem *)messageItem
{
    @synchronized (self) {
        
        if (messages.count == 0) {
            messageItem.isDisplayTime = YES;
            [messages addObject:messageItem];
            return;
        }
        
        //取出最后一个消息
        GPMessageItem *lastMessageItem = messages.lastObject;
        
        //比较两个的时间戳是否大于5分钟
        messageItem.isDisplayTime = (messageItem.message.localTime - lastMessageItem.message.localTime > 5 * 60 * 1000);
        
        //追加
        [messages addObject:messageItem];
        
    }
}

/**完善消息的头像和昵称*/
- (GPMessageItem *)gp_setupMessageUserInfo:(EMMessage *)message
{
    GPMessageItem *messageItem = [[GPMessageItem alloc] initWithMessage:message];
    
    //根据消息的发送方向设置头像和昵称
    KPartyView *partyView = [KPartyView unarchive];
    NSString *nick = partyView.realName;
    NSString *avatorURLPath = partyView.profile;
    if (!messageItem.isSender) {
        //从本地数据库中加载对方的昵称和头像信息
        NSString *fromHid = messageItem.message.from;
        NSArray *array = [GPProfileItem selectDBWithHid:fromHid];
        if (array.count) {
            GPProfileItem *item = array.firstObject;
            nick = item.name;
            avatorURLPath = item.avatarURL;
        }
    }
    messageItem.nickname = nick;
    messageItem.avatarURLPath = avatorURLPath;

    return messageItem;
}


#pragma mark - 消息发送
/**发送文本消息*/
- (GPMessageItem *)sendTextMessage:(NSString *)text to:(NSString *)to conversationId:(NSString *)conversationId chatType:(EMChatType)chatType progress:(void(^)(int progress))progress completion:(void(^)(GPMessageItem *messageItem ,EMMessage *message, EMError *error))completion
{
    //构造文字消息消息体
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:text];
    
    //生成Message
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:conversationId from:from to:to body:body ext:nil];
    message.chatType = chatType;// 设置消息类型
//    message.ext      = @{@"uid":[UserManager currentUser].uid};
    
    //生成GPMessageItem并设置其他属性
    GPMessageItem *messageItem = [self gp_setupMessageUserInfo:message];
    
    //发送消息
    [[EMClient sharedClient].chatManager sendMessage:message progress:progress completion:^(EMMessage *message, EMError *error) {
        if (completion) {
            completion(messageItem,message,error);
        }
    }];
    
    //返回创建好的模型
    return messageItem;
}

/**发送图片消息*/
- (GPMessageItem *)sendImageMessage:(UIImage *)originImage thumbnailImage:(UIImage *)thumbnail to:(NSString *)to conversationId:(NSString *)conversationId chatType:(EMChatType)chatType progress:(void(^)(int progress))progress completion:(void(^)(GPMessageItem *messageItem ,EMMessage *message, EMError *error))completion
{
    //构造图片消息消息体
    NSData *originData = UIImagePNGRepresentation(originImage);
//    NSData *thumbData  = UIImagePNGRepresentation(thumbnail);
//    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:originData thumbnailData:thumbData];
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:originData displayName:@"image.png"];
    
    //生成message
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:conversationId from:from to:to body:body ext:nil];
    message.chatType = chatType;
    
    //生成GPMessageItem并设置其他属性
    GPMessageItem *messageItem = [self gp_setupMessageUserInfo:message];
    
    //发送消息
    [[EMClient sharedClient].chatManager sendMessage:message progress:progress completion:^(EMMessage *message, EMError *error) {
        if (completion) {
            completion(messageItem,message,error);
        }
    }];
    
    return messageItem;
}

/**发送语音消息*/
- (GPMessageItem *)sendVoiceMessage:(NSString *)audioPath displayName:(NSString *)fileName duration:(int)duration conversationId:(NSString *)conversationId to:(NSString *)to chatType:(EMChatType)chatType progress:(void(^)(int progress))progress completion:(void(^)(GPMessageItem *messageItem ,EMMessage *message, EMError *error))completion
{
    EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithLocalPath:audioPath displayName:fileName];
    body.duration = duration;
    NSString *from = [[EMClient sharedClient] currentUsername];
    
    // 生成message
    EMMessage *message = [[EMMessage alloc] initWithConversationID:conversationId from:from to:to body:body ext:nil];
    message.chatType = chatType;// 设置为单聊消息
    
    //生成GPMessageItem并设置其他属性
    GPMessageItem *messageItem = [self gp_setupMessageUserInfo:message];
    
    //发送消息
    [[EMClient sharedClient].chatManager sendMessage:message progress:progress completion:^(EMMessage *message, EMError *error) {
        if (completion) {
            completion(messageItem,message,error);
        }
    }];
    
    return messageItem;
}


/**发送地址消息*/
- (GPMessageItem *)sendLocationMessageLatitude:(double)latitude longitude:(double)longitude address:(NSString *)address name:(NSString *)name to:(NSString *)to conversationId:(NSString *)conversationId chatType:(EMChatType)chatType progress:(void(^)(int progress))progress completion:(void(^)(GPMessageItem *messageItem ,EMMessage *message, EMError *error))completion
{
    //创建定位消息消息体
    EMLocationMessageBody *body = [[EMLocationMessageBody alloc] initWithLatitude:latitude longitude:longitude address:address];
    
    //生成message
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:conversationId from:from to:to body:body ext:nil];
    message.chatType = chatType;
    message.ext = @{@"name":name};
    
    //生成GPMessageItem并设置其他属性
    GPMessageItem *messageItem = [self gp_setupMessageUserInfo:message];
    
    //发送消息
    [[EMClient sharedClient].chatManager sendMessage:message progress:progress completion:^(EMMessage *message, EMError *error) {
        if (completion) {
            completion(messageItem,message,error);
        }
    }];
    
    return messageItem;
}

/**发送SOS紧急消息*/
- (GPMessageItem *)sendSOSMessage:(UIImage *)originImage latitude:(double)latitude longitude:(double)longitude address:(NSString *)address to:(NSString *)to conversationId:(NSString *)conversationId chatType:(EMChatType)chatType progress:(void(^)(int progress))progress completion:(void(^)(GPMessageItem *messageItem ,EMMessage *message, EMError *error))completion
{
    //构造图片消息消息体
    NSData *originData = UIImagePNGRepresentation(originImage);
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:originData displayName:@"image.png"];
    
    //生成message
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:conversationId from:from to:to body:body ext:nil];
    message.chatType = chatType;
    message.ext = @{@"address":address,
                    @"latitude":@(latitude),
                    @"longitude":@(longitude)};
    
    //生成GPMessageItem并设置其他属性
    GPMessageItem *messageItem = [self gp_setupMessageUserInfo:message];
    
    //发送消息
    [[EMClient sharedClient].chatManager sendMessage:message progress:progress completion:^(EMMessage *message, EMError *error) {
        if (completion) {
            completion(messageItem,message,error);
        }
    }];
    
    return messageItem;
}


#pragma mark - 消息接收-EMChatManagerDelegate
/*!
 @method
 @brief 接收到一条及以上非cmd消息
 */
- (void)messagesDidReceive:(NSArray *)aMessages
{
    //解析普通消息
    NSMutableArray *arrayM = [NSMutableArray array];
    for (EMMessage *message in aMessages) {
        
        //创建并解析message
        GPMessageItem *messageItem = [self gp_setupMessageUserInfo:message];
        
        //添加到数组中
        [arrayM addObject:messageItem];
    }
    
    //更新数据源并刷新表格
    for (GPMessageItem *messageItem in arrayM) {
        
        //添加数据源
        [self messageArray:self.messages addMessage:messageItem];
        
        //刷新表格
        [self.tableView reloadData];
    }
    
    //滚动
    if (self.messages.count != 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

/*!
 @method
 @brief 接收到一条及以上cmd消息
 */
- (void)cmdMessagesDidReceive:(NSArray *)aCmdMessages
{
    
}




@end
